/*
 * @Author: Xujianchen
 * @Date: 2024-09-19 11:00:31
 * @LastEditors: xujianchen
 * @LastEditTime: 2024-09-19 11:12:07
 * @Description: 观察元素尺寸指令
 */
// EXPLAIN: 使用WeakMap当卸载后能够被回收
const map = new WeakMap()
const ob = new ResizeObserver((entries) => {
  for (const entry of entries) {
    const handler = map.get(entry.target)
    handler &&
      handler({
        ...entry.contentRect,
        width: entry.borderBoxSize[0].inlineSize,
        height: entry.borderBoxSize[0].blockSize,
      })
  }
})

export default {
  mounted(el, binding) {
    map.set(el, binding.value)
    ob.observe(el)
  },
  unmounted(el) {
    ob.unobserve(el)
  },
}
